package com.itwn.portal.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itwn.common.constant.RedisConst;
import com.itwn.portal.model.entity.China;
import com.itwn.portal.service.ChinaService;
import com.itwn.portal.mapper.ChinaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 61073
* @description 针对表【t_china】的数据库操作Service实现
* @createDate 2024-12-18 14:10:06
*/
@Service
public class ChinaServiceImpl extends ServiceImpl<ChinaMapper, China>
    implements ChinaService{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 面试题： Redis在你项目中的应用？？？
     * ====> 省份缓存数据，zset
     *
     * Redis存储中国的所有省份缓存：
     * 1、不能重复
     * 2、有序
     * 3、数据类型？ zset
     *      key: xxx
     *      score: 分值，通过分值保证顺序。
     *      value: 省份
     */
    @Override
    public List<China> getAllProvince() {
        List<China> chinaList = null;
        // 当Redis中没有数据时候，执行查询数据库
        if (!redisTemplate.hasKey(RedisConst.PROVINCES)) {
            chinaList = this.lambdaQuery()
                    .eq(China::getPid, 0)
                    .ne(China::getId, 0)
                    .orderByAsc(China::getId).list();
            // 查询结果放入Redis缓存中
            chinaList.forEach(china -> {
                redisTemplate.opsForZSet().add(RedisConst.PROVINCES, china, china.getId());
            });
        } else {
            // 从Redis中获取数据
            Set<China> set = redisTemplate.opsForZSet().range(RedisConst.PROVINCES, 0, -1);
            chinaList = new ArrayList<>(set);
        }

        return chinaList;
    }

    /**
     * 根据省份的id查询所有城市
     */
    @Cacheable(value = RedisConst.CITIES, key = "#root.methodName + #provinceId")
    @Override
    public List<China> getAllCities(Integer provinceId) {
        List<China> list = this.list(Wrappers.lambdaQuery(China.class).eq(China::getPid, provinceId));
        return list;
    }

    @Cacheable(value = RedisConst.DISTRICTS, key = "#root.methodName + #p0")
    @Override
    public List<China> getAllDistricts(Integer cityId) {
        List<China> list = this.list(
                Wrappers.lambdaQuery(China.class).eq(China::getPid, cityId));
        return list;
    }

    @Cacheable(value = RedisConst.CHINA_CACHE, key = "#id")
    @Override
    public China findById(Integer id) {
        return this.getById(id);
    }
}




